package com.elf.zero.widget;

import android.content.Context;
import android.graphics.Color;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.elf.zero.app.AbsLinearLayout;
import com.elf.zero.app.R;

import java.util.ArrayList;
import java.util.List;

public class BottomTabWidget extends AbsLinearLayout {

    private List<View> viewList;
    private List<TextView> textViewList;
    private List<ImageView> imageViewList;
    private int mSelectedIndex;
    private int normalColor,selectedColor;

    private OnTabSelectedListener mOnTabSelectedListener;

    public BottomTabWidget(Context context) {
        super(context);
    }

    public BottomTabWidget(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    protected int getLayoutResId() {
        return R.layout.zero_widget_bottom_tab;
    }

    @Override
    protected void initView(AttributeSet attrs) {
        normalColor = getResources().getColor(R.color.zero_bottom_tab_normal_color);
        selectedColor= getResources().getColor(R.color.colorPrimary);

        viewList = new ArrayList<>();
        textViewList = new ArrayList<>();
        imageViewList = new ArrayList<>();
        mSelectedIndex = -1;

        LinearLayout rootLayout = getViewById(R.id.root_layout);
        for (int i = 0; i < rootLayout.getChildCount(); i++) {
            ViewGroup view = (ViewGroup) rootLayout.getChildAt(i);
            TextView tv = (TextView) view.getChildAt(1);
            view.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    setSelectIndex(viewList.indexOf(v));
                }
            });
            viewList.add(view);
            textViewList.add(tv);
            imageViewList.add((ImageView) view.getChildAt(0));
        }

        setSelectIndex(0);
    }


    public void setSelectIndex(int index) {
        if (mSelectedIndex == index) {
            if (mOnTabSelectedListener != null) {
                mOnTabSelectedListener.onReSelected(mSelectedIndex);
            }
            return;
        }
        mSelectedIndex = index;

        for (int i = 0; i < viewList.size(); i++) {
            imageViewList.get(i).setColorFilter(i == mSelectedIndex ? selectedColor : normalColor);
            textViewList.get(i).setTextColor(i == mSelectedIndex ? selectedColor : normalColor);
        }

        if (mOnTabSelectedListener != null) {
            mOnTabSelectedListener.onSelected(mSelectedIndex);
        }
    }

    public void setOnTabSelectedListener(OnTabSelectedListener listener) {
        mOnTabSelectedListener = listener;
    }

    public interface OnTabSelectedListener {
        void onSelected(int index);

        void onReSelected(int index);
    }
}
